#include "strlib.h"

char *mystrcpy(char *dest, char *src) {
    char *pdes = dest;
    if (dest == NULL || src == NULL) return NULL;
    while ((*pdes++ = *src++) != '\0')
        ;
    return dest;
}

int mystrcmp(char *s1, char *s2) {
    for (; *s1 == *s2; ++s1, ++s2)
        if (*s1 == '\0') return 0;
    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}

u32 mystrlen(char *str) {
    u32 i;
    for (i = 0; str[i] != '\0'; i++)
        ;
    return i;
}

char *mystrcat(char *dest, char *src) {
    char *pdes = dest;
	  if (dest == NULL || src == NULL) return NULL;
    while (*pdes != '\0') pdes++;
    while ((*pdes++ = *src++) != '\0');
    return dest;
}

void *mymemcpy2(void *dest, void *src, u32 n) {   
    u8 *pdes = (u8 *)dest;
    u8 *psrc = (u8 *)src;
	  if (dest == NULL || src == NULL || n == 0) return NULL;
    while (n--) *pdes++ = *psrc++;
    return dest;
}

char* mystrstr(char* src, char* sub, u32 maxLength) {
    char *bp;
    char *sp;
    if(!src || !sub) return src;
    while(*src && maxLength) {
        bp = src;
        sp = sub;
        do {
            if(!*sp) return src;
        } while(*bp++ == *sp ++);
        src ++;
        maxLength --;
    }
    return NULL;
}

// str to u32 number, radix = 10
u32 str2num(char *str) {
    u32 i = 0, result = 0;
    for (; str[i] != '\0'; i++) {
        if (str[i] == ' ')
            continue;  // skip ' ';
        else if (str[i] == '+')
            continue;  // skip ' ';
        else if (str[i] == '-')
            continue;  // skip ' ';
        else
            break;
    }
    for (; str[i] != '\0'; i++) {
        if (str[i] >= '0' && str[i] <= '9')
            result = 10 * result + (str[i] - '0');
        else
            break;
    }
    return result;
}

// u32 num to str
char *num2str(u32 num, char *str, u8 radix) {
    char index[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    u16 i = 0, j = 0, k = 0;
    char tmp;
    while (num) {
        str[i++] = index[num % radix];
        num /= radix;
    }
    str[i] = '\0', k = i / 2;
    for (j = 0; j < k; j++) {
        tmp = str[j];
        str[j] = str[i - j - 1];
        str[i - j - 1] = tmp;
    }
    return str;
}